package com.kfm.kfmspringboot.controller;

import com.kfm.kfmspringboot.controller.validate.Insert;
import com.kfm.kfmspringboot.model.entity.User;
import com.kfm.kfmspringboot.model.response.ResponseCode;
import com.kfm.kfmspringboot.model.response.ResultVO;
import com.kfm.kfmspringboot.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    // @PostMapping("/addUser")
    // @ResponseBody
    public ResultVO<String> addUser(@RequestBody @Validated User user, BindingResult bindingResult) {
        // 如果有参数校验失败，会将错误信息封装成对象组装在BindingResult里
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        if (!allErrors.isEmpty()) {
            return ResultVO.failure(ResponseCode.VALIDATE_ERROR_CODE, "参数校验错误", allErrors.stream()
                    .map(o -> o.getDefaultMessage())
                    .collect(Collectors.toList()).toString());
        }
        // 返回默认的错误信息
        return ResultVO.success(allErrors.get(0).getDefaultMessage());
    }

    @PostMapping("/addUser")
    @ResponseBody
    public ResultVO<String> addUser(@RequestBody @Validated({Insert.class}) User user) {
        int i = userService.addUser(user);
        if (i > 0) {
            return ResultVO.success("新增成功！");
        }
        return ResultVO.failure("新增用户失败！");
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public ResultVO<List<User>> all() {
        List<User> all = userService.findAll();
        if (all != null) {
            return ResultVO.success("查询成功", all);
        }
        return ResultVO.failure(ResponseCode.SERVER_ERROR_CODE,"查询失败");
    }
}
